package haoyc.handler;

import haoyc.config.SessionManagement;
import haoyc.entity.Response;
import haoyc.entity.SimpleMouseEvent;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Memory
 * @version 1.0
 * @date 2021/11/23
 */

@Slf4j
@ChannelHandler.Sharable
public class MouseEventHandler extends SimpleChannelInboundHandler<SimpleMouseEvent> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SimpleMouseEvent msg) throws Exception {
        Channel clientChannel = SessionManagement.getClientChannel(ctx.channel());
        // 如果双方都在线
        if (clientChannel != null) {
            // 通过接收方与服务器之间的channel发送信息
            clientChannel.writeAndFlush(msg);
        } else {
            // 通过发送方与服务器之间的channel发送消息
            ctx.writeAndFlush(new Response("404", "对方用户不存在或离线，发送失败"));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage(), cause);
        Channel channel = ctx.channel();
        if (channel.isActive()) {
            ctx.close();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        super.channelReadComplete(ctx);
    }

}
